import { createSlice } from '@reduxjs/toolkit'
import type { PayloadAction } from '@reduxjs/toolkit'
import type { RootState } from './index'
import { PayParam } from '@/types/payCenter'
import { encode, decode } from 'js-base64'

interface PayCenterState {
  payParam: Partial<PayParam>
  payPrice: string
  payTimeSpan: number
  startPayTime: number //to do storelocalstang
}
let state = {} as any
const idCode = localStorage.getItem('idCode')
if (idCode != undefined && idCode != '') {
  state = { ...JSON.parse(decode(idCode)) }
}
const now = Date.now()
const initialState: PayCenterState = {
  payParam: {},
  payPrice: '',

  startPayTime: 0,
  ...state,
  payTimeSpan: 15 * 60 * 1000 - (now - state.startPayTime),
}

export const payCenterSlice = createSlice({
  name: 'counter',
  initialState,
  reducers: {
    setPayParam: (state, action: PayloadAction<Partial<PayParam>>) => {
      state.payParam = { ...state.payParam, ...action.payload }
      localStorage.setItem('idCode', encode(JSON.stringify(state)))
    },
    setStartPayTime: (state, action: PayloadAction<number>) => {
      state.startPayTime = action.payload
      const now = Date.now()
      state.payTimeSpan = 15 * 60 * 1000 - (now - action.payload)
      localStorage.setItem('idCode', encode(JSON.stringify(state)))
    },
    setPayPrice: (state, action: PayloadAction<string>) => {
      state.payPrice = action.payload
    },
    setPayTimeSpan: (state, action: PayloadAction<number>) => {
      state.payTimeSpan = action.payload
      localStorage.setItem('idCode', encode(JSON.stringify(state)))
    },
    clearPayStatus: (state) => {
      state.payPrice = ''
    },
    setLocalstorage: (state) => {
      localStorage.setItem('idCode', encode(JSON.stringify(state)))
    },
  },
})

export const { setPayParam, setPayPrice, setPayTimeSpan, setLocalstorage, setStartPayTime } =
  payCenterSlice.actions
export const selectPayParam = (state: RootState) => state.payCenter.payParam
export const selectPayTimeSpan = (state: RootState) => state.payCenter.payTimeSpan
export const selectPayPrice = (state: RootState) => state.payCenter.payPrice
export const selectStartPayTime = (state: RootState) => state.payCenter.startPayTime
export default payCenterSlice.reducer
